package wallet

import (
	"context"
	"github.com/zeromicro/go-zero/core/mr"
	"go.uber.org/zap"
	gamePb "navi-mumbai/app/rpc/game/pb"
	"navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/xerr"
	"time"

	"navi-mumbai/app/api/business/internal/svc"
	"navi-mumbai/app/api/business/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRefreshGameWalletLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserRefreshGameWalletLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRefreshGameWalletLogic {
	return &UserRefreshGameWalletLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserRefreshGameWalletLogic) UserRefreshGameWallet(req *types.UserRefreshGameWalletReq) (resp *types.UserRefreshGameWalletResp, err error) {
	if len(req.List) == 0 {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "no data")
	}
	uid := ctxdata.GetUidFromCtx(l.ctx)
	if uid != req.List[0].Uid {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "no privilege")
	}

	fns := make([]func() error, 0)
	rsps := make([]*gamePb.GetGameWalletBalanceResp, len(req.List))
	for i := 0; i < len(req.List); i++ {
		ic := i
		fns = append(fns, func() error {
			var in gamePb.GetGameWalletBalanceReq
			in.Uid = req.List[ic].Uid
			in.ProviderId = req.List[ic].ProviderId
			in.MoneyType = req.List[ic].MoneyType
			rsps[ic], err = l.svcCtx.GameWalletRpc.GetGameWalletBalance(l.ctx, &in)
			if err != nil {
				l.Logger.Errorf("err == ", zap.Error(err))
				return err
			}
			//
			var in2 pb.UpdateGameWalletBalanceReq
			in2.Uid = req.List[ic].Uid
			in2.ProviderId = req.List[ic].ProviderId
			in2.MoneyType = req.List[ic].MoneyType
			in2.MoneyAmount = rsps[ic].Balance
			_, err = l.svcCtx.WalletUsersRpc.UpdateGameWalletBalance(l.ctx, &in2)
			if err != nil {
				l.Logger.Errorf("err == ", zap.Error(err))
				return err
			}
			return nil
		})
	}
	err = mr.Finish(fns...)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.ServerCommonError, err.Error())
	}
	resp = &types.UserRefreshGameWalletResp{
		List: make([]*types.GameWallet, len(req.List)),
	}
	for i := 0; i < len(req.List); i++ {
		resp.List[i] = &types.GameWallet{
			ProviderId: req.List[i].ProviderId,
			MoneyType:  req.List[i].MoneyType,
			Balance:    rsps[i].Balance,
			UpdateTime: time.Now().Format(dbkey.DateTimeCNFormat),
		}
	}

	return
}
